<template>
	<public-view navType="other" navTitle="发视频">
		<view class="content flex f-d-c">
			<view class="tip-box f-s-24  color-999">
				<text class="xing">*</text>视频名称
			</view>
			<view class="video-name-box flex a-i-c">
				<view class="title f-s-28 f-w-b">
					视频名称
				</view>
				<input type="text" class="f-s-24" placeholder-class="color-999" placeholder="请输入视频名称" v-model="title">
			</view>
			<view class="tip-box f-s-24  color-999">
				
				<text class="xing">*</text>上传视频
			</view>
			<view class="video-upload-box all-center" @click="handleVideo">
				<image class="add-icon" src="@/static/images/live/white-add-icon.svg" mode="" v-if="!screenshot"></image>
				<image style="width:100%;height:100%" :src="screenshot" mode="" v-else></image>
			</view>
			<view class="video-tip color-666 f-s-26">
				视频长度不可超过10分钟
			</view>
			<view class="tip-box f-s-24  color-999">
				<text class="xing">*</text>背景音乐
			</view>
			<view class="video-name-box flex a-i-c j-c-b" @click="goTo({url:'/pages/live/bgMusic/index?checked_id='+music.id})">
				<view class="flex a-i-c">
					<view class="title f-s-28 f-w-b">
						背景音乐
					</view>
					<input type="text" :disabled="true" class="f-s-24" placeholder-class="color-999" :placeholder="music.name">
				</view>
				<view class="">
					<image class="bgmusic-next" src="@/static/images/next-icon3.svg" mode=""></image>
				</view>
			</view>
			<bottom-btn :positon="true" @click.stop="requestData">发布</bottom-btn>
		</view>
	</public-view>
</template>

<script>
	import bottomBtn from "@/components/myComponents/bottomBtn.vue"
	import {goTo} from "@/nav.js"
	import { guid } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import md5 from 'md5'
	// #ifdef APP
	import {
	    executeFFmpeg,
		getMediaInformation
	} from '@/uni_modules/sn-uts-ffmpeg'
	// #endif
	export default {
		components:{
			"bottom-btn":bottomBtn
		},
		data() {
			return {
				title:'',
				music:{
					id:0,
					name:'请选择背景音乐',
					url:'',
					duration:'0.00'
				},
				video:'',
				screenshot:'',
				screenshot_path:'',
				video_path:'',
				screenshot_path:'',
				guid:'',
				file_name:'',
				find:''
			};
		},
		onLoad(){
			// #ifdef APP
				this.init()
			// #endif
		},
		onBackPress() {
			uni.$off('find_select_music')
		},
		onUnload() {
			uni.$off('find_select_music')
		
		},
		methods:{
			goTo,
			init() {
				let that = this
				uni.$on('find_select_music',(data) => {
					that.music = data
					console.log(that.music)
				})
				
				this.video_path = plus.io.convertLocalFileSystemURL('_doc/find/video')
				that.removeCache()
				this.music_path = plus.io.convertLocalFileSystemURL('_doc/find/music')
				that.screenshot_path = plus.io.convertLocalFileSystemURL('_doc/find/screenshot/')
				plus.io.resolveLocalFileSystemURL( '_doc/', (entry) => {
					entry.getDirectory( "find/screenshot/", {create:true,exclusive:false}, function( dir ){
						console.log("创建成功: " + dir.name);
					}, function (e) {
						console.log("创建失败: " + e.message );
					} );
					entry.getDirectory( "find/video/", {create:true,exclusive:false}, function( dir ){
						console.log("创建成功: " + dir.name);
					}, function (e) {
						console.log("创建失败: " + e.message );
					} );
				}, (err) => {
					console.log(err)
				} );
			},
			
			handleVideo() {
				uni.chooseVideo({
					success: ch => {
						let that = this
						if (Math.trunc(ch.duration) < 10) {
							uni.showToast({
								icon:'none',
								title:'视频时长不能小于10秒'
							})
							return;
						}
						if (Math.trunc(ch.duration) > 600) {
							uni.showToast({
								icon:'none',
								title:'视频时长不能超过10分钟'
							})
							return;
						}
						let select_temp_video_path = plus.io.convertLocalFileSystemURL(ch.tempFilePath)
						
						let cmd = `-i ${select_temp_video_path} -y -f image2 -frames 1 ${that.screenshot_path}screenshot.jpg`
						// 封装ffmpeg命令
						executeFFmpeg(cmd, (res) => {
							if (res.state == 3 && res.returnCode == 0) {
								that.screenshot = that.screenshot_path + 'screenshot.jpg'
								that.video = select_temp_video_path
							} else {
								uni.showToast({
									icon:'none',
									title:'获取视频信息失败'
								})
							}
							
						},(res) => {
							// console.log("统计信息回调：" + JSON.stringify(res));
						},(res) => {
							// console.log("开始任务回调：" + JSON.stringify(res));
						},(res) => {
							// console.log("log回调：" + JSON.stringify(res));
						});
					}

					
				})
			},
			requestData() {
				let that = this
				if (that.title === '') {
					uni.showToast({
						icon:'none',
						title:'请输入标题'
					})
					return
				}
				
				if (that.music.id == 0) {
					uni.showToast({
						icon:'none',
						title:'请选择背景音乐'
					})
					return
				}
				
				if (that.video == '') {
					uni.showToast({
						icon: 'none',
						title:'请选择视频'
					})
					return
				}
				
				that.makeVideo(() => {
					
				})
				
			},
			makeVideo(callback) {
				let that = this
				let url_arr = that.music.url.split('.')
				let ext = url_arr[url_arr.length-1]
				let file_name = md5(that.music.id) + '.' + ext;
				let tfn = that.music_path + '/' + file_name
				let tfnu = plus.io.convertAbsoluteFileSystem(tfn)
				uni.showLoading({
					title:'正在合成视频',
					mask: true
				})
				uni.getFileInfo({
					filePath:tfnu,// 必填，临时文件路径，不支持 res: 开头的文件路径。
					success:res=>{
						// console.log(res)
						that.make(tfn)
					},//必填，获取成功的回调函数
					fail:(err)=>{
						that.dowM(that.music.url,tfnu,(res) => {
							// console.log(res)
							that.make(tfn)
						})
					},// 必填，获取失败的回调函数
					complete:()=>{}// 非必填，API 调用结束的回调函数（调用成功、失败都会执行）
				})
			},
			
			make(music){
				let that = this
				// 调用原生插件获取视频时长
				getMediaInformation(that.video, (res) => {
					let duration = 0;
					try{
						duration = Math.trunc(res.info.allProperties.nameValuePairs.format.nameValuePairs.duration);
					}catch(e) {
						uni.showToast({
							icon:'none',
							title:'获取视频信息失败'
						})
						uni.hideLoading()
						return
					}
					that.guid = guid()
					that.file_name = that.guid+'.mp4'
						// console.log(res);
					that.find = that.video_path + '/' + that.file_name + '_.mp4'
					
					let cmd = `-i ${that.video} -stream_loop -1 -i ${music} -filter_complex [0:a][1:a]amix -c:a aac -c:v libx264 -profile:v high -r 30 -crf 30 -s 720x1280 -movflags +faststart -strict experimental -t ${duration} -y  ${that.find}`;
					// 封装ffmpeg命令
					executeFFmpeg(cmd, (res) => {
						uni.hideLoading()
						if (res.state == 3 && res.returnCode == 0) {
							
							uni.showToast({
								title:'生成成功',
								icon:'none'
							})
							this.up()
							
						} else {
							uni.showToast({
								icon:'none',
								title:'生成失败'
							})
							
						}
						// that.tempPath = makeTempPath
						
						//执行完成去调用上传
						// that.up(name,new_tempFilePath)
						
					},(res) => {
						// console.log("统计信息回调：" + JSON.stringify(res));
					},(res) => {
						// console.log("开始任务回调：" + JSON.stringify(res));
					},(res) => {
						// console.log("log回调：" + JSON.stringify(res));
					});
				},(res)=>{
					// console.log(res);
				});
			},
			
			up() {
				let that = this
				uni.showLoading({
					title:'上传中...',
					mask: true
				});
				that.util.postRequest({
					url:'v1/video/getUploadProof',
					data:{
						name:that.file_name
					}
				}).then(res => {
					let sts = res.data
					let uploadTask = uni.uploadFile({
						url: sts.ossUrl, 
						filePath: that.find,
						name: sts.file,
						formData: sts.formData,
						success: upload => {
							if(upload.statusCode === 200){
								// this.params.video_id = sts.videoId;
								// this.video.tempFilePath = ch.tempFilePath;
								that.addFind(sts.videoId)
							}else{
								
								uni.showToast({
									title:'上传失败',
									icon:'none'
								})
								uni.hideLoading()
							}
					
							
						},
						fail: (res) => {
							console.info(res);
						}
					});
				})
			},
			addFind(video_id,content) {
				let that = this
				uni.showLoading({
					title:'发布作品中',
					mask:true
				})
				that.util.postRequest({
					url:'v1/find/add',
					data:{
						type:'video',
						video_id:video_id,
						content:that.title
					}
				}).then(res => {
					uni.hideLoading()
						if (res.code == 1) {
							uni.showToast({
								title:res.msg,
								icon:'none'
							})
						}
					
					let t = setTimeout(() => {
						
						if (res.code == 1) {
							
							uni.navigateBack()
						} else {
							that.$router.go(0)
							
						}
						clearTimeout(t)
					},1000)
					
				}).catch(err => {
					uni.showToast({
						title:err.msg,
						icon:'none'
					})
				})
			},
			removeCache() {
				//这里进入页面时把旧的东西清了
				plus.io.resolveLocalFileSystemURL( plus.io.convertAbsoluteFileSystem(this.video_path), (entry) => {
					entry.removeRecursively( (r) => {
						console.log(r,'删除成功')
					}, (e) => {
						console.log(e)
					} )
				}, (err) => {
					console.log(err)
				} );
			},
			
			dowM(url,tfnu,callback) {
				let dtask = plus.downloader.createDownload(url,{filename:tfnu},(d,status) => {
					if(status==200){
						callback(d)
					}else{	
						//下载失败
						
						uni.hideLoading()
						uni.showToast({
							title:'下载失败',
							icon:'none'
						})
					}
					dtask = null
					plus.downloader.clear();        //清除下载任务
				})
				dtask.start()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bgmusic-next{
		width: 48upx;
		height: 48upx;
	}
	.video-upload-box{
		width: 100%;
		height: 622upx;
		border-radius: 12upx;
		background: #e4e4e4;
		margin-bottom: 20upx;
		.add-icon{
			width: 92upx;
			height: 92upx;
		}
	}
	.video-name-box{
		width: 100%;
		padding: 42upx 40upx;
		background: #FFFFFF;
		border-radius: 12upx;
		margin-bottom: 20upx;
		.title{
			margin-right: 36upx;
		}
	}
	.video-tip{
		margin-bottom: 32upx;
	}
	.tip-box{
		margin-bottom: 14upx;
		.xing{
			color: #F32B2B;
		}
	}
	.content{
		padding: 30upx;
		width: 100%;
	}
</style>
